package com.bite.common.file.config;

import com.aliyun.oss.*;
import com.aliyun.oss.common.auth.*;
import com.aliyun.oss.common.comm.SignVersion;
import com.aliyuncs.exceptions.ClientException;
import jakarta.annotation.PreDestroy;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;

@Slf4j
@Component
public class OSSConfig {
            // yourEndpoint填写Bucket所在地域对应的Endpoint。以华东1（杭州）为例，Endpoint填写为https://oss-cn-hangzhou.aliyuncs.com。
    @Autowired
    private OSSProperties prop;

    public OSS ossClient;
    @Bean
    public  OSS ossClient() throws ClientException {
            // 从环境变量中获取访问凭证。运行本代码示例之前，请先配置环境变量。
        DefaultCredentialProvider credentialsProvider= CredentialsProviderFactory.newDefaultCredentialProvider(
                    prop.getAccessKeyId(),prop.getAccessKeySecret()
            );

            // 创建OSSClient实例。
        ClientBuilderConfiguration clientBuilderConfiguration = new ClientBuilderConfiguration();
            // 显式声明使用 V4 签名算法
        clientBuilderConfiguration.setSignatureVersion(SignVersion.V4);
        OSS ossClient = OSSClientBuilder.create()
                    .endpoint(prop.getEndpoint())
                    .credentialsProvider(credentialsProvider)
                    .clientConfiguration(clientBuilderConfiguration)
                    .region(prop.getRegion())
                    .build();

        return ossClient;
        }
    // 关闭OSSClient。
    @PreDestroy
    public void  closeOSSClient() {
        ossClient.shutdown();
    }
}
